<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/21
 * Time: 14:08
 * Auth: YWH
 */

namespace App\Models;


use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;


class MachineGoodsModel extends Model
{
    public $table = "machine_goods";
    public static $error;

    public function getGoodsListByMachineId(int $machine_id)
    {
        $data = self::query()
            ->where('machine_id',$machine_id)
            ->join('goods','goods.goods_id','=','machine_goods.goods_id')
            ->where('marketable','=',1)
            ->orderBy('box_id','asc')
            ->get(
                [
                    'goods.goods_id',
                    'goods.goods_name',
                    'goods.price',
                    'machine_goods.machine_id',
                    'machine_goods.box_id',
                    'machine_goods.box_status',
                    DB::raw('IFNULL(discount_price,price) discount_price')
                ]
            );
        foreach ($data as &$val){
            $val['box_status'] = $val['box_status']==1?"有货":"无货";
        }
        return $data;
    }

    public function delMachineFromHotel(int $machine_id)
    {
      return MachineModel::unbind_machine(['machine_id'=>$machine_id]);
    }

    /**应用模板
     * @param $hotel_id
     * @param $machine_id
     * @return bool
     * @throws \Exception
     */
    public static function apply_template($hotel_id,$machine_id)
    {
        $need_to_apply_goods = false;
        if(!empty($hotel_id)){
            $need_to_apply_goods = true;
            $machine_list  = MachineModel::searchMachineList([
                'machine.hotel_id' => $hotel_id
            ],'',false);
            $machine_id_arr = array_column($machine_list,'machine_id');
        }else{
            $machine_id_arr = [$machine_id];
        }

        $template_arr = Template::list()->toArray();
        if($template_arr){
            $template_arr = $template_arr[0];
        }else{
            $template_arr = [];
            self::$error = '还没有创建模板';
            return false;
        }

        DB::beginTransaction();
        try{
            foreach($machine_id_arr as $machine_id){
                $mac_goods_model = self::query()->where('machine_id','=',$machine_id)->first();
                $machineModel = MachineModel::find($machine_id);
                $hotel_id = $machineModel -> hotel_id;

                #有记录说明已经插入过了
                if($mac_goods_model){
                    #直接更新
                    for($i = 1 ; $i <= 6 ; $i++ ){
                        $res = self::query()
                            ->where('machine_id','=',$machine_id)
                            ->where('box_id','=',$i)
                            ->update([
                                'goods_id' => $template_arr['box'.$i],
                            ]);
                        if(!$res){
                            throw new \Exception('更新machine_goods表中machine_id为'.$machine_id.'的记录失败');
                        }
                    }
                }else{
                    #没有记录
                    $insert_data = [];
                    for($i = 1 ; $i <= 6 ; $i++ ){
                        $insert_data[] = [
                            'box_id'     => $i,
                            'machine_id' => $machine_id,
                            'goods_id'   => $template_arr['box'.$i],
                            'hotel_id'   => $hotel_id,
                            'mac'        => $machineModel -> mac,
                        ];
                    }
                    $res = DB::table('machine_goods')
                        -> insert($insert_data);
                    if(!$res){
                        throw  new \Exception('插入machine_good中的machine_id为'.$machine_id.'的记录失败');
                    }
                }
            }

            if($need_to_apply_goods){
                $res = self::apply_hotel_goods($hotel_id,$template_arr);
            }
            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            dd($exception-> getMessage());
            self::$error = $exception -> getMessage();
            return false;
        }
    }

    /**
     * 将模板商品运用于该酒店
     */
    public static function apply_hotel_goods($hotel_id,$template_arr)
    {
            $goods_id_arr = [];
            $hotelModel = Hotel::find($hotel_id);
            if(!$hotelModel){
                throw new \Exception('酒店id为'.$hotel_id.'不存在!');
            }

            #模板-商品id列表
            for($i = 1; $i <= 6; $i++){
                $templte_goods_id_arr[] = $template_arr['box'.$i];
            }

            #去重重复的模板商品id
            $templte_goods_id_arr = array_unique($templte_goods_id_arr);

            $hotel_goods_arr = HotelGoods::hotel_goods_list([
                'hotel.hotel_id' => $hotel_id,
            ]);

            $update_data = [];
            $hotel_goods_id_arr = array_column($hotel_goods_arr,'goods_id');

            #一.需要暂停出售的商品
            $off_sale_goods_id_arr = array_diff($hotel_goods_id_arr,$templte_goods_id_arr);

            #二.需要更新为出售的商品
            $tobeupdated_goods_id_arr = array_intersect($hotel_goods_id_arr,$templte_goods_id_arr);

            #三.需要插入的商品
            $tobeinserted_goods_id_arr = array_diff($templte_goods_id_arr,$hotel_goods_id_arr);

            #执行步骤一
            if(!empty($off_sale_goods_id_arr)){
                $res = HotelGoods::query()
                    -> where('hotel_id','=',$hotel_id)
                    -> whereIn('goods_id',$off_sale_goods_id_arr)
                    -> update(['is_on_sale'=>0]);
                if(!$res){
                    throw new \Exception('执行步骤一，更新需要暂停出售的商品失败!');
                }
            }

            #执行步骤二
            if(!empty($tobeupdated_goods_id_arr)){
                $res = HotelGoods::query()
                    -> where('hotel_id','=',$hotel_id)
                    -> whereIn('goods_id',$tobeupdated_goods_id_arr)
                    -> update(['is_on_sale'=>1]);
                if(!$res){
                    throw new \Exception('执行步骤二，更新需要出售的商品失败!');
                }
            }

            #执行步骤三
            if(!empty($tobeinserted_goods_id_arr)){
                $insert_data = [];
                foreach($tobeinserted_goods_id_arr as $insert_goods_id){
                    $insert_data[] = ['hotel_id'=> $hotel_id,'goods_id' => $insert_goods_id];
                }
                $res = DB::table('hotel_goods')->insert($insert_data);
                if(!$res){
                    throw new \Exception('执行步骤三,插入需要出售的商品失败!');
                }
            }
            return true;
    }



    /**
     * 设置设备格子有货，无货
     */
    public static function setting_box_status($postData)
    {
        if(!isset($postData[0])){
            $res =  self::query()
                ->where('machine_id','=',$postData['machine_id'])
                ->where('box_id','=',$postData['box_id'])
                ->update(['box_status'=>$postData['box_status']]);
            if(!$res){
                self::$error = '批量设置失败';
                return false;
            }
            return true;
        }

        DB::beginTransaction();
        try{
            //传递过来的是二维数组，则为批量设置
            foreach($postData as $arr){
                $res = self::query()
                    ->where('machine_id','=',$arr['machine_id'])
                    ->update(['box_status'=>$arr['box_status']]);
                if(!$res){
                    throw  new \Exception('批量设置machine_id为'.$arr['machine_id'].'的box_status为'.$arr['box_status'].'失败');
                }
            }

            DB::commit();
            return true;
        }catch (\Exception $exception){
            DB::rollBack();
            self::$error = $exception -> getMessage();
            return false;
        }
    }






}